# -*- coding: utf-8 -*-
"""
简化加密工具模块 - 使用固定密钥，避免密钥文件问题
"""
import base64
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

class SimpleEncryptionManager:
    """简化加密管理器 - 使用固定密钥"""
    
    def __init__(self):
        self._init_fernet()
    
    def _init_fernet(self):
        """初始化Fernet加密器"""
        # 使用固定的盐值和密码生成密钥
        salt = b"mysql_dict_2024_salt"  # 固定盐值
        password = b"mysql_dict_export_tool_2024"  # 固定密码
        
        # 使用PBKDF2生成密钥
        kdf = PBKDF2HMAC(
            algorithm=hashes.SHA256(),
            length=32,
            salt=salt,
            iterations=100000,
        )
        
        key = base64.urlsafe_b64encode(kdf.derive(password))
        self.fernet = Fernet(key)
    
    def encrypt_password(self, password):
        """加密密码"""
        try:
            if not password:
                return ""
            
            encrypted_password = self.fernet.encrypt(password.encode('utf-8'))
            return base64.b64encode(encrypted_password).decode('utf-8')
        except Exception as e:
            print(f"密码加密失败: {e}")
            return None
    
    def decrypt_password(self, encrypted_password):
        """解密密码"""
        try:
            if not encrypted_password:
                return ""
            
            encrypted_data = base64.b64decode(encrypted_password.encode('utf-8'))
            decrypted_password = self.fernet.decrypt(encrypted_data)
            return decrypted_password.decode('utf-8')
        except Exception as e:
            print(f"密码解密失败: {e}")
            return None
    
    def is_encrypted(self, text):
        """检查文本是否已加密"""
        try:
            if not text:
                return False
            
            # 尝试解码base64
            base64.b64decode(text.encode('utf-8'))
            return True
        except:
            return False

# 创建全局加密管理器实例
encryption_manager = SimpleEncryptionManager()
